package com.luyuan.wxapp.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.luyuan.common.annotation.Anonymous;
import com.luyuan.common.constant.HttpStatus;
import com.luyuan.common.core.domain.AjaxResult;
import com.luyuan.common.core.page.TableDataInfo;
import com.luyuan.common.utils.PageUtils;
import com.luyuan.common.utils.SecurityUtils;
import com.luyuan.gallery.domain.ExhiComment;
import com.luyuan.gallery.param.CommentParam;
import com.luyuan.gallery.service.IExhiCommentService;
import com.luyuan.gallery.service.IExhiCommentLikeService;
import com.luyuan.gallery.vo.HierarchicalCommentVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 评论业务Controller
 * 
 * @author luyuan
 * @date 2025-11-06
 */
@Api(value = "微信小程序评论接口", tags = "wx_comment")
@RestController
@RequestMapping("/wxapp/comment")
public class WxappExhiCommentController extends WxBaseController {

    @Autowired
    private IExhiCommentService exhiCommentService;

    @Autowired
    private IExhiCommentLikeService exhiCommentLikeService;

    /**
     * 添加评论
     */
    @ApiOperation(value = "添加评论", notes = "添加评论", nickname = "addComment")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody ExhiComment exhiComment) {
        int rows = exhiCommentService.insertExhiComment(exhiComment);
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 根据用户ID查询评论列表
     */
    @ApiOperation(value = "根据用户ID查询评论列表", notes = "根据用户ID查询评论列表", nickname = "listComment")
    @GetMapping("/list")
    public TableDataInfo listCommentByUserId(CommentParam commentParam) {
        startPage();
        Long userId = SecurityUtils.getWxappLoginUser().getUserId();
        List<ExhiComment> list = exhiCommentService.selectExhiCommentListByUserId(userId);
        return getDataTable(list);
    }

    /**
     * 根据targetId查询评论列表（支持两级评论和分页）
     */
    @Anonymous
    @ApiOperation(value = "根据targetId查询评论列表", notes = "根据targetId查询评论列表（支持两级评论和分页）", nickname = "treeComment")
    @GetMapping("/tree")
    public TableDataInfo listComment(CommentParam commentParam) {
        commentParam.setRootId(0L);
        // 分页处理
        PageUtils.startPage();
        // 获取所有评论
        List<HierarchicalCommentVO> allComments = exhiCommentService.selectExhiCommentListByTargetId(commentParam);
        // 由于我们已经获取了所有数据，这里需要手动分页
        PageInfo<HierarchicalCommentVO> pageInfo = PageInfo.of(allComments);
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(pageInfo.getList());
        rspData.setTotal(pageInfo.getTotal());
        // 构建层级评论结构
        Pair<List<HierarchicalCommentVO>, Long> resultPair = buildHierarchicalComments(allComments,
                pageInfo.getTotal());
        rspData.setRows(resultPair.getLeft());
        rspData.setTotal(resultPair.getRight());
        return rspData;
    }

    /**
     * 构建层级评论结构
     * 
     * @param comments 原始评论列表
     * @return 层级评论列表
     */
    private Pair<List<HierarchicalCommentVO>, Long> buildHierarchicalComments(List<HierarchicalCommentVO> comments,
            long total) {
        // 按照rootId分组，用于快速查找子评论
        List<HierarchicalCommentVO> rootComments = new ArrayList<>();
        for (HierarchicalCommentVO comment : comments) {
            CommentParam childCommentParam = new CommentParam();
            childCommentParam.setRootId(comment.getId());
            List<HierarchicalCommentVO> childComments = exhiCommentService
                    .selectExhiCommentListByTargetId(childCommentParam);
            comment.setReplies(childComments);
            rootComments.add(comment);
            total = total + childComments.size();
        }
        Pair<List<HierarchicalCommentVO>, Long> result = Pair.of(rootComments, total);
        return result;
    }

    /**
     * 点赞或取消点赞评论
     */
    @ApiOperation(value = "点赞或取消点赞评论", notes = "点赞或取消点赞评论", nickname = "likeComment")
    @PostMapping("/like")
    public AjaxResult likeOrUnlike(@RequestBody CommentParam commentParam) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getWxappLoginUser().getUserId();
        int rows = exhiCommentLikeService.likeOrUnlikeComment(commentParam.getId(), userId);
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 删除评论（逻辑删除）
     */
    @ApiOperation(value = "删除评论（逻辑删除）", notes = "删除评论（逻辑删除）", nickname = "deleteComment")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestBody CommentParam commentParam) {
        int rows = exhiCommentService.deleteExhiCommentById(commentParam.getId());
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }
}